<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 栅格布局 -->
      <el-row :gutter="20">
        <!-- 第一列 -->
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            @clear="getUserList"
            v-model="queryData.query"
            @change="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 第二列 -->
        <el-col :span="4">
          <el-button type="primary" @click="isShow = true">新增用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <!-- 表格组件遍历数组生成表格行 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <!-- 会将当前行数据对象传给row属性，并将插槽中的代码渲染到当前单元格中 -->
          <template slot-scope="ele">
            <el-switch
              v-model="ele.row.mg_state"
              @change="changeState(ele.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="showEditDialog(row.id)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUser(row.id)"
            ></el-button>
            <el-tooltip content="设置权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="showSetRoleDialog(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码条 -->
      <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageChange"
        :current-page.sync="queryData.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="isShow"
        width="30%"
        @close="closeDialog"
      >
        <!-- 新增表单 -->
        <el-form
          ref="addFormRef"
          :model="addFormData"
          :rules="addRules"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addFormData.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFormData.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFormData.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addFormData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShow = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户的对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="closeEditDialog"
      >
        <el-form
          :model="editForm"
          :rules="editRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
      >
        <div>
          <p>当前用户：{{ currentUser.username }}</p>
          <p>当前角色：{{ currentUser.role_name }}</p>
          <p>
            分配的角色：
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="setRole">确定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data: function () {
    // 手机号规则检查函数
    const mobleRuleCheck = (rule, value, cb) => {
      const p = /^1[3|5|7|8|9]\d{9}$/
      if (p.test(value)) return cb()
      cb(new Error('请输入合法手机号'))
    }
    return {
      // 用户列表查询参数对象
      queryData: {
        query: '', // 查询参数
        pagenum: 1, // 当前页码
        pagesize: 2 // 页容量
      },
      userList: [], // 用户数组
      total: 0, // 总用户数
      isShow: false, // 是否显示新增对话框
      addFormData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      }, // 表单数据对象
      addRules: {
        // 表单校验规则对象
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ], // 内置规则
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: mobleRuleCheck, trigger: 'blur' }
        ] // 自定义规则函数
      },
      editDialogVisible: false,
      // 表单对象
      editForm: {},
      // 表单验证规则
      editRules: {
        // 表单校验规则对象
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ], // 内置规则
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: mobleRuleCheck, trigger: 'blur' }
        ] // 自定义规则函数
      },
      setRoleDialogVisible: false,
      currentUser: {}, // 当前用户
      roleList: [], // 角色列表
      selectRoleId: '' // 选中的角色id
    }
  },
  methods: {
    // 异步请求 用户列表
    async getUserList () {
      // 发送异步请求，并解构返回对象中的data属性，赋值给resBody
      const { data: resBody } = await this.$http.get('users', {
        params: this.queryData
      })
      // 如果失败，则显示错误消息，并退出函数执行
      if (resBody.meta.status !== 200) {
        return this.$msg.error(resBody.meta.msg)
      }
      // 如果成功，则将返回的分页数据设置给组件的data,触发视图的重绘
      this.userList = resBody.data.users
      // 将返回的总用户数量设置给data
      this.total = resBody.data.total
    },
    pageSizeChange (newPageSize) {
      // 将选择的新的页容量，设置给data
      this.queryData.pagesize = newPageSize
      // 重新请求当前页数据
      this.getUserList()
    },
    pageChange (newPageIndex) {
      // 将被点击的页码设置给data
      this.queryData.pagenum = newPageIndex
      // 重新请求当前页数据
      this.getUserList()
    },
    // 状态改变事件（参数：状态改变的行数据对象）
    async changeState (rowData) {
      console.log(rowData)
      const { data: resBody } = await this.$http.put(
        `users/${rowData.id}/state/${rowData.mg_state}`
      )
      // 如果请求修改失败
      if (resBody.meta.status !== 200) {
        rowData.mg_state = !rowData.mg_state
        return this.$msg.error(resBody.meta.msg)
      }
      // 如果成功
      this.$msg.success(resBody.meta.msg)
    },
    closeDialog () {
      // 关闭对话框事件
      // vue内部的获取dom元素的方法
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      // 添加用户
      // 校验表单
      this.$refs.addFormRef.validate(async isOk => {
        // 如果校验失败，则退出函数
        if (!isOk) {
          return false
        }
        // 如果校验成功，则发送异步请求
        const { data: resBody } = await this.$http.post(
          'users',
          this.addFormData
        )
        // 如果添加失败，则返回
        if (resBody.meta.status !== 201) {
          return this.$msg.error(resBody.meta.msg)
        }
        // 如果添加成功，则重新请求渲染列表
        this.getUserList()
        // 关闭窗口
        this.isShow = false
        // 提示消息
        this.$msg.success(resBody.meta.msg)
      })
    },
    async showEditDialog (id) {
      // console.log(id)
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      this.editForm = res.data
    },
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },
    editUser () {
      this.$refs.editFormRef.validate(async isOk => {
        if (isOk) {
          // 发请求
          const { data: res } = await this.$http.put(
            'users/' + this.editForm.id,
            {
              email: this.editForm.email,
              mobile: this.editForm.mobile
            }
          )
          // 验证修改是否成功
          if (res.meta.status !== 200) {
            // 通过elme代码片段
            return this.$message({
              message: '编辑失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          }
          // 成功提示
          this.$message({
            message: '编辑成功',
            type: 'success',
            showClose: true,
            duration: 3000
          })
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新列表
          this.getUserList()
        } else {
        }
      })
    },
    deleteUser (id) {
      // 确认是否删除
      // 通过elemcon书写确认对话框
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async action => {
          // 点击确定
          // 发请求
          await this.$http.delete('users/' + id)
          // 刷新请求
          this.getUserList()
        })
        .catch(error => {
          console.log('error', error)
          this.$msg({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showSetRoleDialog (row) {
      this.currentUser = row
      this.setRoleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },
    async setRole () {
      // 请求
      await this.$http.put(`users/${this.currentUser.id}/role`, {
        rid: this.selectRoleId
      })
      // 提示
      this.$message({
        message: '操作成功',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      // 刷新列表
      this.getUserList()
      // 关闭对话框
      this.setRoleDialogVisible = false
    }
  },
  // 钩子函数
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less"></style>
